package com.wbao.dianniu.utils;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.media.MediaMetadataRetriever;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.ContextCompat;
import android.telephony.TelephonyManager;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.baidu.mapapi.http.HttpClient;
import com.google.gson.JsonObject;
import com.wbao.dianniu.R;
import com.wbao.dianniu.adapter.NoScrollGridAdapter;
import com.wbao.dianniu.customView.CanDoBlankGridView;
import com.wbao.dianniu.customView.HtmlTextView;
import com.wbao.dianniu.customView.SpanTextView;
import com.wbao.dianniu.data.AnswerUserInfo;
import com.wbao.dianniu.data.LoginResponse;
import com.wbao.dianniu.data.Martis;
import com.wbao.dianniu.data.SortByIndex;
import com.wbao.dianniu.data.SpanData;
import com.wbao.dianniu.data.WorkExperienceData;
import com.wbao.dianniu.logical.GlobalContext;
import com.wbao.dianniu.logical.GlobalUserData;
import com.wbao.dianniu.viewpager.MyViewPager;

import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.FileDescriptor;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Utils {

    //	static final String TAG = "Utils";
    public static final String DIRECTORY;
    public static final ExecutorService SERVICE;
    private static final String WORKSPLIT = "\\|.\\|\\|\\|.\\|";
    private static final String DATASPLIT = ".\\|\\|\\|.";

    static {
        SERVICE = Executors.newCachedThreadPool();
        String DCIM = Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_DCIM).toString();
        DIRECTORY = DCIM + "/Camera";
    }

    /**
     * 频繁获取同文件，同时间的截图，可以尝试Memory cache bitmap，提高速度，
     *
     * @param filePath
     * @param fd
     * @param timeUs
     * @return
     */
    public static Bitmap createVideoThumbnail(String filePath,
                                              FileDescriptor fd, long timeUs) {
        Bitmap bitmap = null;
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        try {
            if (filePath != null) {
                retriever.setDataSource(filePath);
            } else {
                retriever.setDataSource(fd);
            }
            bitmap = retriever.getFrameAtTime(timeUs);
        } catch (Throwable throwable) {
            // Assume this is a corrupt video file
        } finally {
            try {
                retriever.release();
            } catch (RuntimeException ex) {
            }
        }
        return bitmap;
    }


    public static Martis getMetrics(WindowManager manager) {
        DisplayMetrics metric = new DisplayMetrics();
        manager.getDefaultDisplay().getMetrics(metric);
        int width = metric.widthPixels; // 屏幕宽度（像素）
        int height = metric.heightPixels; // 屏幕高度（像素）
//		float density = metric.density; // 屏幕密度（0.75 / 1.0 / 1.5）
//		int densityDpi = metric.densityDpi; // 屏幕密度DPI（120 / 160 / 240）
        Martis martis = new Martis();
        martis.setWidth(width);
        martis.setHeight(height);
        return martis;
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * 获取网落图片资源
     *
     * @param url
     * @return
     */
    public Bitmap getHttpBitmap(String url) {
        URL myFileURL;
        Bitmap bitmap = null;
        try {
            myFileURL = new URL(url);
            // 获得连接
            HttpURLConnection conn = (HttpURLConnection) myFileURL
                    .openConnection();
            // 设置超时时间为6000毫秒，conn.setConnectionTiem(0);表示没有时间限制
            conn.setConnectTimeout(6000);
            // 连接设置获得数据流
            conn.setDoInput(true);
            // 不使用缓存
            conn.setUseCaches(false);
            // 这句可有可无，没有影响
            // conn.connect();
            // 得到数据流
            InputStream is = conn.getInputStream();
            // 解析得到图片
            bitmap = BitmapFactory.decodeStream(is);
            // 关闭数据流
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }

    public boolean isMobile(String mobile) {
        return mobile.matches("^(13|15|18|14|17)\\d{9}$");
    }

    public static String Md5(String str) {
        byte[] hash;
        try {
            hash = MessageDigest.getInstance("MD5").digest(str.getBytes("UTF-8"));
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("Huh, MD5 should be supported?", e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("Huh, UTF-8 should be supported?", e);
        }

        StringBuilder hex = new StringBuilder(hash.length * 2);
        for (byte b : hash) {
            if ((b & 0xFF) < 0x10)
                hex.append("0");
            hex.append(Integer.toHexString(b & 0xFF));
        }
        return hex.toString();
    }

    public static String inputStream2String(InputStream is, String charset) {
        ByteArrayOutputStream baos = null;
        try {
            baos = new ByteArrayOutputStream();
            int i = -1;
            while ((i = is.read()) != -1) {
                baos.write(i);
            }
            return baos.toString(charset);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != baos) {
                try {
                    baos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                baos = null;
            }
        }
        return null;
    }

    public static int getMaxCounts(String str, Context context) {
        int position = -1;
        String[] section_arrays = context.getResources().getStringArray(R.array.activity_peoples_array);
        for (int i = 0; i < section_arrays.length; i++) {
            if (section_arrays[i].equals(str)) {
                position = i;
                break;
            }
        }
        if (-1 != position) {
            int[] maxCounts = context.getResources().getIntArray(R.array.activity_peoples_ID);
            return maxCounts[position];
        } else {
            return position;
        }
    }


    /**
     * 为字体改变颜色
     *
     * @param textView
     * @param content
     */
    public static void TextColorShow(TextView textView, String content) {
        SpannableStringBuilder builder = new SpannableStringBuilder(textView.getText().toString());
        //ForegroundColorSpan 为文字前景色，BackgroundColorSpan为文字背景色
        ForegroundColorSpan redSpan = new ForegroundColorSpan(Color.RED);
        int start = textView.getText().toString().trim().indexOf(content);
        builder.setSpan(redSpan, start, start + content.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        textView.setText(builder);
    }


    public static String getFormatDate(String date) {
        if (date.length() >= 10) {
            return date.substring(0, 10);
        } else {
            return "";
        }
    }

    public static void saveLoginData(Context context, LoginResponse objdata) {
        // 新增积分返回
        GlobalUserData userData = new GlobalUserData();
        userData.setScore(objdata.getAccountInfo().getScore());
        userData.setEnvironment(objdata.getEnvironmentName());
        userData.setBeFriend(objdata.getAccountInfo().getBeFriend());
        userData.setPerfectResume(objdata.getAccountInfo().getIsPerfectResume());
        userData.setDataprivacy(objdata.getAccountInfo().getDataPrivacy());
        userData.setMobile(objdata.getAccountInfo().getMobile());
        userData.setResumeStatus(objdata.getAccountInfo().getResumeStatus());
        userData.setVersionCode(objdata.getVersion());
        userData.setPartner(objdata.getAccountInfo().getPartner());
        userData.setUserSig(objdata.getTencentImUserSig());

        GlobalContext.cleanCacheToken();
        // 保存用户数据
        GlobalContext.setCacheToken(objdata.getToken());
        GlobalContext.setCdnToken(objdata.getCdnToken());
        GlobalContext.setAccountId(objdata.getAccountInfo().getId());
        GlobalContext.setHeadPic(objdata.getAccountInfo().getHeadPic());
        GlobalContext.setNiceName(objdata.getAccountInfo().getRealName());
        GlobalContext.setSignate(objdata.getAccountInfo().getDescribe());
        GlobalContext.setLabel(objdata.getAccountInfo().getLabel());
        GlobalContext.setSex(objdata.getAccountInfo().getSex());
        GlobalContext.setPerfectData(objdata.getAccountInfo().isPerfectData());
        GlobalContext.setIndustryAuthority(objdata.getAccountInfo().isIndustryAuthority());

    }

    /**
     * 强制隐藏键盘
     *
     * @param context
     * @param view
     */
    public static void hideSoftInput(Context context, View view) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0); // 强制隐藏键盘
    }


    public static String formatNotifyDate(String date) {
        String result = "";
        if (null == date) {
            return result;
        }
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            SimpleDateFormat format = new SimpleDateFormat("MM月dd日 HH:mm");
            result = format.format(sdf.parse(date));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 格式化时间（面试时间、入职时间、离职时间）
     *
     * @param date
     * @return
     */
    public static String formatDate(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:00");
        String str = format.format(date);
        return str;
    }

    /**
     * @param startDate yyyy-MM-dd HH:mm:ss 格式时间
     * @return true: 活动已结束，false：活动未开始
     */
    public static boolean IsActivityStart(String startDate) {
        boolean ret = false;
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            ret = date.after(format.parse(startDate));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return ret;
    }

    /**
     * @param startDate yyyy-MM-dd HH:mm:ss 格式时间
     * @return true: 结束时间大于起始时间，false：结束时间小于起始时间
     */
    public static boolean IsEndAfterStart(String startDate, String endDate) {
        boolean ret = false;
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date sDate = format.parse(startDate + " 00:00:00");
            Date eDate = format.parse(endDate + " 00:00:00");
            ret = eDate.after(sDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return ret;
    }

    public static List<WorkExperienceData> parseWorkData(String data) {
        List<WorkExperienceData> list = new ArrayList<WorkExperienceData>();
        String[] str = data.split(WORKSPLIT);
        for (int i = 0; i < str.length; i++) {
            String[] jobs = str[i].split(DATASPLIT);
            if (jobs.length == 5) {
                WorkExperienceData jobWorkData = new WorkExperienceData();
                jobWorkData.setId(Integer.valueOf(jobs[0]));
                jobWorkData.setStartDate(jobs[1]);
                jobWorkData.setEndDate(jobs[2]);
                jobWorkData.setPost(jobs[3]);
                jobWorkData.setContent(jobs[4]);
                list.add(jobWorkData);
            }
        }
        return list;
    }

    public static String WorkListDataToString(List<WorkExperienceData> list) {
        String str = "";
        if (list.size() == 0) {
            return str;
        }
        str = list.get(0).getId() + ".|||." + list.get(0).getStartDate() + ".|||." + list.get(0).getEndDate() + ".|||."
                + list.get(0).getPost() + ".|||." + list.get(0).getContent();
        for (int i = 1; i < list.size(); i++) {
            str = str + "|.|||.|" + list.get(i).getId() + ".|||." + list.get(i).getStartDate() + ".|||." + list.get(i).getEndDate() + ".|||."
                    + list.get(i).getPost() + ".|||." + list.get(i).getContent();
        }
        return str;
    }


    @TargetApi(19)
    public static void setTranslucentStatus(Activity context, boolean on) {
        Window win = context.getWindow();
        WindowManager.LayoutParams winParams = win.getAttributes();
        final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        if (on) {
            winParams.flags |= bits;
        } else {
            winParams.flags &= ~bits;
        }
        win.setAttributes(winParams);
    }

    public static void imageBrower(Context context, int position, ArrayList<String> imageUrls) {
        Intent intent = new Intent(context, MyViewPager.class);
        // 图片url,为了演示这里使用常量，一般从数据库中或网络中获取
        intent.putExtra(MyViewPager.EXTRA_IMAGE_URLS, imageUrls);
        intent.putExtra(MyViewPager.EXTRA_IMAGE_INDEX, position);
        context.startActivity(intent);
        ((Activity) context).overridePendingTransition(R.anim.zoom_enter, 0);
    }

    public static void praiseChanged(Context context, int falg, int counts, TextView praiseTV) {
        if (1 == falg) {
            Drawable right_draw = context.getResources().getDrawable(R.drawable.click_praise_icon_sel);
            right_draw.setBounds(0, 0, right_draw.getMinimumWidth(), right_draw.getMinimumHeight());
            praiseTV.setCompoundDrawables(right_draw, null, null, null);
        } else {
            Drawable right_draw = context.getResources().getDrawable(R.drawable.click_praise_icon_nor);
            right_draw.setBounds(0, 0, right_draw.getMinimumWidth(), right_draw.getMinimumHeight());
            praiseTV.setCompoundDrawables(right_draw, null, null, null);
        }
        showPriseCounts(counts, praiseTV);
    }

    /**
     * 显示浏览，评论，点赞数
     *
     * @param goodCount
     * @param praiseTV
     */
    public static void showPriseCounts(int goodCount, TextView praiseTV) {
        if (goodCount > 10000) {
            float conts = (float) Math.ceil(goodCount / 1000.0);
            DecimalFormat fnum = new DecimalFormat("##0.0");
            if (conts % 10 > 0) {
                praiseTV.setText(fnum.format(conts / 10) + "万");
            } else {
                praiseTV.setText((int) conts / 10 + "万");
            }
        } else {
            praiseTV.setText(goodCount + "");
        }
    }

    /**
     * 显示转发数
     *
     * @param forwardCount
     * @param praiseTV
     */
    public static void showForwardCounts(int forwardCount, TextView praiseTV) {
        if (forwardCount > 10000) {
            float conts = (float) Math.ceil(forwardCount / 1000.0);
            DecimalFormat fnum = new DecimalFormat("##0.0");
            if (conts % 10 > 0) {
                praiseTV.setText(fnum.format(conts / 10) + "万");
            } else {
                praiseTV.setText((int) conts / 10 + "万");
            }
        } else {
            praiseTV.setText(forwardCount + "");
        }
    }

    /**
     * 显示浏览数
     *
     * @param counts
     * @param tv
     */
    public static void showVisitorCounts(int counts, TextView tv) {
        if (counts > 10000) {
            float conts = (float) Math.ceil(counts / 1000.0);
            DecimalFormat fnum = new DecimalFormat("##0.0");
            if (conts % 10 > 0) {
                tv.setText(fnum.format(conts / 10) + "万人看过");
            } else {
                tv.setText((int) conts / 10 + "万人看过");
            }
        } else {
            tv.setText(counts + "人看过");
        }
    }

    public static Integer getNumberFromString(String str) {
        String regEx = "[^0-9]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return Integer.valueOf(m.replaceAll("").trim());
    }

    public static boolean isNetworkAvaiable(Context context) {
        NetworkInfo var1;
        return (var1 = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo()) != null && var1.isAvailable() && var1.isConnected();
    }

    /**
     * 获取软件版本名
     *
     * @param context
     * @return
     */
    public static String getVersionName(Context context) {
        String versionName = "";
        try {
            versionName = context.getPackageManager().getPackageInfo("com.wbao.dianniu", 0).versionName;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }

        return versionName;
    }

    /**
     * 获取软件版本号
     *
     * @param context
     * @return
     */
    public static int getVersionCode(Context context) {
        int versionCode = 0;
        try {
            versionCode = context.getPackageManager().getPackageInfo("com.wbao.dianniu", 0).versionCode;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;
    }

    /**
     * 问答列表span
     *
     * @param context
     * @param content
     * @param noticeJson
     * @param textview
     * @return
     */
    public static boolean showSpanContent(final Context context, final String content, String noticeJson, SpanTextView textview) {
        boolean isNeed = false;
        if (TextUtils.isEmpty(content)) {
            return isNeed;
        }
        if (TextUtils.isEmpty(noticeJson)) {
            textview.setText(content);
            return isNeed;
        }
        textview.setText(content);
        Map<String, String> map = new HashMap<String, String>();
        ArrayList<SpanData> spanList = new ArrayList<SpanData>();
        try {
            JSONObject jsonObject = new JSONObject(noticeJson);
            Iterator iterator = jsonObject.keys();
            String key = null;
            String value = null;
            while (iterator.hasNext()) {
                key = (String) iterator.next();
                value = jsonObject.getString(key);
                map.put(key, value);
                String keyColorStr = "@" + value;
                int index = 0;
                int start = 0;
                while (content.indexOf(keyColorStr, start) >= 0) {
                    SpanData spanData = new SpanData();
                    index = content.indexOf(keyColorStr, start);
                    spanData.setIndex(index);
                    spanData.setCounts(keyColorStr.length());
                    spanData.setAccountId(Integer.valueOf(key));
                    spanData.setVaule(value);
                    spanList.add(spanData);
                    start = index + keyColorStr.length();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (spanList.size() > 0) {    // 排序
            Collections.sort(spanList, new SortByIndex());
            for (int j = 0; j < spanList.size(); j++) {
                textview.setSpanLink(spanList.get(j).getVaule(), String.valueOf(spanList.get(j).getAccountId()), false, spanList.get(j).getIndex(), spanList.get(j).getCounts());
                textview.setOnLinkClickListener(new SpanTextView.onLinkClickListener() {
                    @Override
                    public void onLinkClick(View view, String text, String sign) {
                        int accountId = Integer.valueOf(sign);
                        ActivityUtils.intoHeadInfoActivity(accountId, context);
                    }
                });
            }
            isNeed = true;
        } else {
        }
        return isNeed;
    }

    /**
     * 问答列表span
     *
     * @param context
     * @param content
     * @param noticeJson
     * @param textview
     * @return
     */
    public static boolean showHtmlSpanContent(final Context context, final String content, String noticeJson, HtmlTextView textview) {
        boolean isNeed = false;
        if (TextUtils.isEmpty(content)) {
            return isNeed;
        }
        if (TextUtils.isEmpty(noticeJson)) {
            textview.setText(content);
            return isNeed;
        }
        textview.setText(content);
        Map<String, String> map = new HashMap<String, String>();
        ArrayList<SpanData> spanList = new ArrayList<SpanData>();
        try {
            JSONObject jsonObject = new JSONObject(noticeJson);
            Iterator iterator = jsonObject.keys();
            String key = null;
            String value = null;
            while (iterator.hasNext()) {
                key = (String) iterator.next();
                value = jsonObject.getString(key);
                map.put(key, value);
                String keyColorStr = "@" + value;
                int index = 0;
                int start = 0;
                while (content.indexOf(keyColorStr, start) >= 0) {
                    SpanData spanData = new SpanData();
                    index = content.indexOf(keyColorStr, start);
                    spanData.setIndex(index);
                    spanData.setCounts(keyColorStr.length());
                    spanData.setAccountId(Integer.valueOf(key));
                    spanData.setVaule(value);
                    spanList.add(spanData);
                    start = index + keyColorStr.length();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (spanList.size() > 0) {
            SpannableString spannableString = new SpannableString(content);
            // 排序
            Collections.sort(spanList, new SortByIndex());
            for (int j = 0; j < spanList.size(); j++) {
                spannableString.setSpan(new ForegroundColorSpan(Color.parseColor("#057dff")), spanList.get(j).getIndex(), spanList.get(j).getIndex() + spanList.get(j).getCounts(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
//                textview.setSpanLink(spanList.get(j).getVaule(), String.valueOf(spanList.get(j).getAccountId()), false, spanList.get(j).getIndex(), spanList.get(j).getCounts());
                /*textview.setOnLinkClickListener(new SpanTextView.onLinkClickListener() {
                    @Override
                    public void onLinkClick(View view, String text, String sign) {
                        int accountId = Integer.valueOf(sign);
                        intoHeadInfoActivity(accountId, context);
                    }
                });*/
                textview.setText(spannableString);
            }
            isNeed = true;
        } else {
        }
        return isNeed;
    }


    /**
     * 问答详情span
     *
     * @param context
     * @param content
     * @param noticeJson
     * @param textview
     * @return
     */
    public static boolean showSpanContentNoClick(final Context context, String content, String noticeJson, SpanTextView textview) {
        boolean isNeed = false;
        if (TextUtils.isEmpty(content)) {
            return isNeed;
        }
        if (TextUtils.isEmpty(noticeJson)) {
            textview.setText(content);
            return isNeed;
        }
        textview.setText(content);
        Map<String, String> map = new HashMap<String, String>();
        ArrayList<SpanData> spanList = new ArrayList<SpanData>();
        try {
            JSONObject jsonObject = new JSONObject(noticeJson);
            Iterator iterator = jsonObject.keys();
            String key = null;
            String value = null;
            while (iterator.hasNext()) {
                key = (String) iterator.next();
                value = jsonObject.getString(key);
                map.put(key, value);
                String keyColorStr = "@" + value;
                int index = 0;
                int start = 0;
                while (content.indexOf(keyColorStr, start) >= 0) {
                    SpanData spanData = new SpanData();
                    index = content.indexOf(keyColorStr, start);
                    spanData.setIndex(index);
                    spanData.setCounts(keyColorStr.length());
                    spanData.setAccountId(Integer.valueOf(key));
                    spanData.setVaule(value);
                    spanList.add(spanData);
                    start = index + keyColorStr.length();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (spanList.size() > 0) {    // 排序
            Collections.sort(spanList, new SortByIndex());
//            SpannableString spanString = new SpannableString(content);
            for (int j = 0; j < spanList.size(); j++) {
//				spanString.setSpan(new ClickSpan(context,spanList.get(j)), spanList.get(j).getIndex(), spanList.get(j).getIndex() + spanList.get(j).getCounts(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                textview.setSpanLink(spanList.get(j).getVaule(), String.valueOf(spanList.get(j).getAccountId()), false, spanList.get(j).getIndex(), spanList.get(j).getCounts());
                textview.setOnLinkClickListener(new SpanTextView.onLinkClickListener() {
                    @Override
                    public void onLinkClick(View view, String text, String sign) {
                        int accountId = Integer.valueOf(sign);
                        ActivityUtils.intoHeadInfoActivity(accountId, context);
                    }
                });
            }
            isNeed = true;
        } else {
        }
        return isNeed;
    }

    /**
     * 回复内容span
     *
     * @param context
     * @param content
     * @param noticeJson
     * @param textview
     * @param isLinkable
     * @return
     */
    public static boolean showSpanContentComment(final Context context, String content, String noticeJson, SpanTextView textview, boolean isLinkable) {
        boolean isNeed = false;
        if (TextUtils.isEmpty(content)) {
            return isNeed;
        }
        if (TextUtils.isEmpty(noticeJson)) {
            textview.setText(content);
            return isNeed;
        }
        textview.setText(content);
        Map<String, String> map = new HashMap<String, String>();
        ArrayList<SpanData> spanList = new ArrayList<SpanData>();
        try {
            JSONObject jsonObject = new JSONObject(noticeJson);
            Iterator iterator = jsonObject.keys();
            String key = null;
            String value = null;
            while (iterator.hasNext()) {
                key = (String) iterator.next();
                value = jsonObject.getString(key);
                map.put(key, value);
                String keyColorStr = "回复" + value;
                int index = 0;
                int start = 0;
                while (content.indexOf(keyColorStr, start) >= 0) {
                    SpanData spanData = new SpanData();
                    index = content.indexOf(keyColorStr, start);
                    spanData.setIndex(index);
                    spanData.setCounts(keyColorStr.length());
                    spanData.setAccountId(Integer.valueOf(key));
                    spanData.setVaule(value);
                    spanList.add(spanData);
                    start = index + keyColorStr.length();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (spanList.size() > 0) {    // 排序
            Collections.sort(spanList, new SortByIndex());
            SpannableString spanString = new SpannableString(content);
            for (int j = 0; j < spanList.size(); j++) {
                textview.setSpanLink(spanList.get(j).getVaule(), String.valueOf(spanList.get(j).getAccountId()), false, spanList.get(j).getIndex() + 2, spanList.get(j).getCounts() - 2);
                if (isLinkable) {
                    textview.setOnLinkClickListener(new SpanTextView.onLinkClickListener() {
                        @Override
                        public void onLinkClick(View view, String text, String sign) {
                            int accountId = Integer.valueOf(sign);
                            ActivityUtils.intoHeadInfoActivity(accountId, context);
                        }
                    });
                }
            }
            isNeed = true;
        }

        return true;
    }

    public static String getFilePathFromUri(Context context, Uri uri) {
        String filePath = uri.toString();
        //红米Note这里会直接返回文件路径，因此这里需要适配一下(红米Note返回的数据格式为：file:///storage/emulated/0/.....)
        if (!TextUtils.isEmpty(filePath) && filePath.startsWith("file:")) {
            filePath = filePath.substring(7);
            return filePath;
        }
        String[] filePathColumn = {MediaStore.MediaColumns.DATA};

        Cursor cursor = context.getContentResolver().query(uri, filePathColumn, null, null, null);
        cursor.moveToFirst();

        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        filePath = cursor.getString(columnIndex);
        cursor.close();
        return filePath;
    }

    public static String toHeavyNoticeJson(Map<Integer, String> noticeJson, String content) {
        JsonObject jsonObject = new JsonObject();
        for (Map.Entry<Integer, String> entry : noticeJson.entrySet()) {
            String str = "@" + entry.getValue();
            if (content.contains(str)) {
                jsonObject.addProperty(String.valueOf(entry.getKey()), String.valueOf(entry.getValue()));
            }
        }
        String result = "";
        if (!jsonObject.toString().equals("{}")) {
            result = jsonObject.toString();
        }
        return result;
    }


//    public static void showUserInfo(Context mContext, AnswerUserInfo userInfo, UserInfoHolder holder) {
//        if (null == userInfo)
//            return;
//        PictureDownloadUtils.displayHeadImage(mContext, holder.headIV, userInfo.headPic);
//        holder.nameTV.setText(userInfo.realName == null ? "" : userInfo.realName);
//        showSex(mContext, userInfo.sex, holder.sexIV);
//        showPartner(mContext, userInfo.partner, holder.partnerIV);
//        holder.labelTV.setText(userInfo.label == null ? "" : userInfo.label);
//        showAuth(userInfo, holder.addV);
//    }


    public static void showPartner(Context context, int flag, ImageView imageview) {
        if (1 == flag) {
            imageview.setVisibility(View.VISIBLE);
        } else if (0 == flag) {
            imageview.setVisibility(View.GONE);
        }
    }

    public static void showSex(Context context, Integer sexFlag, ImageView imageview) {
        if (null == sexFlag || -1 == sexFlag) {
            imageview.setVisibility(View.GONE);
            return;
        }
        if (0 == sexFlag) {
            imageview.setImageDrawable(context.getResources().getDrawable(R.drawable.girl_icon));
        } else {
            imageview.setImageDrawable(context.getResources().getDrawable(R.drawable.boy_icon));
        }
        imageview.setVisibility(View.VISIBLE);
    }

    /**
     * 显示加V
     *
     * @param userInfo
     * @param addV
     */
    public static void showAuth(AnswerUserInfo userInfo, ImageView addV) {
        if (null == userInfo) {
            addV.setVisibility(View.GONE);
            return;
        }
        if (userInfo.isIndustryAuthority) {
            addV.setVisibility(View.VISIBLE);
        } else {
            addV.setVisibility(View.GONE);
        }
    }


    public static String getQueryParam(String url, String key) {
        Pattern p = Pattern.compile("(?:^|/?|&)" + key + "=([^&]*)(?:&|$)", Pattern.CASE_INSENSITIVE);
        Matcher m = p.matcher(url);
        String matcher = "";
        while (m.find()) {
            matcher = m.group(1);
        }
        return matcher;
    }

    /**
     * 文本输入框字数限制
     *
     * @param context
     * @param editText
     * @param count
     */
    public static void ContentLengthLimit(final Context context, EditText editText, final int count) {
        if (null == editText)
            return;
        InputFilter[] filters = {new InputFilter.LengthFilter(count)};
        editText.setFilters(filters);
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int c) {
                if (s.length() >= count) {
                    String str = String.format(context.getResources().getString(R.string.content_length_limit), count + "");
                    Notification.toast(context, str);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

    }


    public static String getDeviceId(Context context) {
        String deviceId = "";
        TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                String[] permissions = {Manifest.permission.READ_PHONE_STATE};
                // 检查该权限是否已经获取
                int i = ContextCompat.checkSelfPermission(context, permissions[0]);
                // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
                if (i != PackageManager.PERMISSION_GRANTED) {
                    // 如果没有授予该权限，就去提示用户请求
                    // ActivityCompat.requestPermissions((Activity) context, permissions, 321);
                    deviceId = "";
                } else {
                    deviceId = tm.getDeviceId();
                }
            } else {
                deviceId = tm.getDeviceId();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


        return deviceId;
    }

    /**
     * @param mContext
     * @param questImgs
     * @param gridview
     * @param isBlankCLick 空白处是否可点击，用户被父控件捕获点击事件
     */
    public static void showGridView(Context mContext, String questImgs, CanDoBlankGridView gridview, boolean isBlankCLick, boolean isShow) {
        ArrayList<String> imageUrls = PictureDownloadUtils.getInstance().stringToList(questImgs);
        //通过图片张数 设置gridview的高度
        double multiple = Math.ceil((float) imageUrls.size() / GlobalContext.NUMCOLUMNS);
        int height = (int) (Utils.dip2px(mContext, 80) * multiple + (multiple - 1) * Utils.dip2px(mContext, 5));
        int width = 0;
        if (multiple >= 1) {
            width = Utils.dip2px(mContext, 80) * GlobalContext.NUMCOLUMNS + (GlobalContext.NUMCOLUMNS - 1) * Utils.dip2px(mContext, 5);
        } else {
            width = Utils.dip2px(mContext, 80) * imageUrls.size() + (imageUrls.size() - 1) * Utils.dip2px(mContext, 5);
        }
        float hor_padding = mContext.getResources().getDimension(R.dimen.content_space_dp) +
                mContext.getResources().getDimension(R.dimen.content_space_dp);
        width = width + (int) hor_padding;// 加上pendingLeftRight
        float ver_padding = mContext.getResources().getDimension(R.dimen.midden_space_dp);
        height = height + (int) ver_padding;
//        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, height);
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(width, height);
        gridview.setLayoutParams(lp);
        gridview.setAdapter(new NoScrollGridAdapter(mContext, imageUrls, isShow));
        // 点击回帖九宫格，查看大图
        gridview.setOnItemClickListener(new MyItemClickListener(mContext, imageUrls));
        if (isBlankCLick) {
            gridview.setOnTouchInvalidPositionListener(new CanDoBlankGridView.OnTouchInvalidPositionListener() {

                @Override
                public boolean onTouchInvalidPosition(int motionEvent) {
                /*
                 * 当返回false的时候代表交由父级控件处理，当return
				 * true的时候表示你已经处理了该事件并不让该事件再往上传递
				 * 。为了出发listview的item点击就得返回false了
				 */
                    return false;
                }
            });
        }

    }


    public static String replaceLineBlanks(String str) {
        String result = "";
        if (str != null) {
            Pattern p = Pattern.compile("(\n(\\s*?\n)+)");
            Matcher m = p.matcher(str);
            result = m.replaceAll("\n");
        }
        return result;
    }


}
